<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`角色`">
    <div class="main-box">
      <TreeFilter
        label="data"
        id="attr"
        title="部门列表"
        :data="treeFilterData"
        :default-value="initParam.departmentId"
        @change="changeTreeFilter"
      />
      <div class="table-box">
        <span v-if="operationList.length == 0"> 请点击功能项的子节点设置权限 </span>
        <span>
          <el-radio v-model="letSelectAll" label="true" @click="selectAll()">全选</el-radio>
          <el-radio v-model="letOppositeSelect" label="true" @click="oppositeSelect()">反选</el-radio>
        </span>
        <el-checkbox
          v-for="(item,index) in (operationList as any[])"
          :key="index"
          :label="(item.resName as string)"
          v-model="(item.check as number)"
          :change="changeCheck(item)"
        />
        <el-button type="primary" @click="save()" class="fixed-button"> 保存 </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="tsx" name="treeProTable">
import { onMounted, reactive, ref } from "vue";
import { User, OrgManager, RoleManager } from "@/api/interface";
import { genderType } from "@/utils/dict";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, ElNotification } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getUserTreeList, deleteUser, editUser, addUser, getUserStatus, getUserDepartment } from "@/api/modules/user";
import { findUserTreeList } from "@/api/modules/jggl";
import { getResourceByRoleId, findTree, operationFind } from "@/api/modules/accessController";
onMounted(() => {
  getTreeFilter();
});

const drawerVisible = ref(false);
// ProTable 实例
const proTable = ref<ProTableInstance>();

const letSelectAll = ref("false");
const letOppositeSelect = ref("false");

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ departmentId: {}, page: 1, rows: 10, orgType: "" });
const operationList = ref([]);
// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await findTree();
  treeFilterData.value = [data];
  let newRes = JSON.parse(JSON.stringify(data));
  initParam.departmentId = newRes.attr;
};

const resourceList = ref([]);

// 树形筛选切换
const changeTreeFilter = (val: any) => {
  letSelectAll.value = "false";
  letOppositeSelect.value = "false";
  if (val == undefined) {
    ElMessage.error("请选择子节点");
    operationList.value = [];
    return;
  }
  if (val.resNo == undefined) {
    ElMessage.error("请选择子节点");
    operationList.value = [];
    return;
  }
  operationFind(val.resNo).then(res => {
    let newRes = JSON.parse(JSON.stringify(res));
    if (newRes.data.length == 0) {
      ElMessage.error("请选择子节点");
      operationList.value = [];
      return;
    } else {
      (newRes.data as any).forEach(function (element: IOperationList) {
        //let newElement = JSON.parse(JSON.stringify(element));
        // newElement.resNo
        let resNo = element.resNo.toString();
        element.check = (resourceList.value as any).includes(resNo) ? true : false;
      });
      operationList.value = newRes.data;
    }
    console.log(res);
  });
};

export interface IOperationList {
  companyName: string; // 标题
  companyNo: string; // 标题
  functionNo: string; // 标题
  functionResCode: string; // 标题
  lastUpdater: string; // 标题
  resCode: string; // 标题
  resIcon: string; // 标题
  resName: string; // 标题
  resNo: string; // 标题
  resUrl: string; // 标题
  check: boolean;
}

const selectAll = () => {
  let tem = operationList.value;
  tem.forEach(function (element: IOperationList) {
    element.check = true;
  });
  operationList.value = tem;
  letSelectAll.value = "true";
  letOppositeSelect.value = "false";
};
const oppositeSelect = () => {
  let tem = operationList.value;
  tem.forEach(function (element: IOperationList) {
    //element.check=element.check==true?false:true
    element.check = element.check == true ? false : true;
  });
  operationList.value = tem;
  letSelectAll.value = "false";
  letOppositeSelect.value = "true";
};

// changeCheck切换
const changeCheck = (val: any) => {
  console.log("前：" + resourceList.value.join());
  if (val.check == true) {
    if ((resourceList.value as any).includes(val.resNo.toString())) {
    } else {
      (resourceList.value as any).push(val.resNo.toString());
    }
  } else {
    if ((resourceList.value as any).includes(val.resNo.toString())) {
      let index = (resourceList.value as any).indexOf(val.resNo.toString()); // 获取要删除元素的索引
      if (index !== -1) {
        // 确保元素存在于数组中
        (resourceList.value as any).splice(index, 1); // 删除一个元素
      }
    } else {
    }
  }
  console.log("后：" + resourceList.value.join());
};

const selfEmit = defineEmits(["sendData"]);

const save = (row: Partial<OrgManager.ResOrgList> = {}) => {
  //回调数据给父组件
  selfEmit("sendData", resourceList.value.join());
  drawerVisible.value = false;
};
const acceptParams = (roleIds: string, flag: boolean) => {
  console.log(roleIds);
  drawerVisible.value = true;
  letSelectAll.value = "false";
  letOppositeSelect.value = "false";
  if (flag) {
    getResourceByRoleId(roleIds).then(res => {
      resourceList.value = (res as any).split(",");
    });
  } else {
    console.log(resourceList);
    resourceList.value = [];
    let tem = operationList.value;
    tem.forEach(function (element: IOperationList) {
      element.check = false;
    });
    operationList.value = tem;
  }
};

defineExpose({
  acceptParams
});

interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
</script>

<style scoped lang="scss">
.fixed-button {
  position: absolute;
  bottom: 0;
  left: 88%; /* 使按钮居中 */
  transform: translateX(-50%);
}
</style>
